package com.pavel.taskig.client;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;

public class AddTaskTable extends FlexTable implements KeyPressHandler {
	protected Button addTaskButton;
	private TextBox textBox;
	private TextArea textArea;
	private TextBox dateBox;
	private TextBox estimatebox;
	private ListBox statusList;

	public AddTaskTable(Button addTaskButton) {
		super();
		this.addTaskButton = addTaskButton;
		init();
	}

	private void init() {
		this.setText(0, 0, "Title:");
		this.setText(1, 0, "Description:");
		this.setText(3, 0, "Start:");
		this.setText(4, 0, "Estimate:");
		this.setText(5, 0, "Status:");
		textBox = new TextBox();
		this.setWidget(0, 1, textBox);
		textArea = new TextArea();
		this.setWidget(2, 0, textArea);
		this.getFlexCellFormatter().setColSpan(2, 0, 2);
		dateBox = new TextBox();
		this.setWidget(3, 1, dateBox);
		estimatebox = new TextBox();
		this.setWidget(4, 1, estimatebox);
		statusList = new ListBox();
		for (Status s : Status.values()) {
			statusList.addItem(s.name());
		}
		this.setWidget(5, 1, statusList);
		textBox.addKeyPressHandler(this);
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		if (event.getCharCode() == KeyCodes.KEY_ENTER) {
			addTask();
			addTaskButton.setEnabled(true);
		}
	}

	private void addTask() {
		Task task = new Task();
		task.setName(textBox.getName());
		task.setDescription(textArea.getText());
		task.setStartDate(DateTimeFormat.getShortDateFormat().parse(
				dateBox.getText()));
		task.setEstimate(EstimateParser.parse(estimatebox.getText()));
		task.setStatus(Status.valueOf(statusList.getItemText(statusList
				.getSelectedIndex())));
		Window.alert(task.toString());
	}

}
